package com.muyu.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.muyu.common.core.enums.PayStatus;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.system.Vo.DmShoppingStoreVO;
import com.muyu.system.domain.*;
import com.muyu.system.dto.CloseStoreDTO;
import com.muyu.system.dto.DmShoppingStoreDTO;
import com.muyu.system.mapper.*;
import com.muyu.system.service.IDmShoppingStoreService;
import com.muyu.system.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商家信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-13
 */
@Service
@Slf4j
public class DmShoppingStoreServiceImpl implements IDmShoppingStoreService {
    @Autowired
    private DmShoppingStoreMapper dmShoppingStoreMapper;

    @Autowired
    private DanmoProductFootprintMapper danmoProductFootprintMapper;
    @Autowired
    private DanmoUserStoreMapper danmoUserStoreMapper;

    @Autowired
    private SecurityDepositAccountMapper securityDepositAccountMapper;

    @Autowired
    private PremiumOrderMapper premiumOrderMapper;

    @Autowired
    private PremiumAccountMapper premiumAccountMapper;

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    private static final String redis_key = "shopping_store_";
    /**
     * 查询商家信息
     *
     * @param id 商家信息主键
     * @return 商家信息
     */
    @Override
    public DmShoppingStore selectDmShoppingStoreById(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        Long userid = loginUser.getUserid();
        // 查询店铺足迹
        List<DanmoProductFootprint> danmoProductFootprintList = danmoProductFootprintMapper.selectFlagship(userid, id);
        boolean hasTodayRecord = false;
        // 1.先判断一下店铺中是否有该店铺的今天的足迹
        if (danmoProductFootprintList != null && !danmoProductFootprintList.isEmpty()) {
            for (DanmoProductFootprint danmoProductFootprint : danmoProductFootprintList) {
                Date updateTime = danmoProductFootprint.getBrowseTime();
                if (isToday(updateTime)) {
                    // 将更新时间修改为当前时间
                    danmoProductFootprint.setUpdateTime(DateUtils.getNowDate());
                    danmoProductFootprintMapper.updateDanmoProductFootprint(danmoProductFootprint);
                    hasTodayRecord = true;
                }
            }
        }
        if (!hasTodayRecord) {
            DanmoProductFootprint build = DanmoProductFootprint.builder()
                    .userId(userid)
                    .shopsId(id)
                    .browseTime(DateUtils.getNowDate())
                    .types(2L)
                    .createTime(DateUtils.getNowDate())
                    .build();
            danmoProductFootprintMapper.insertDanmoProductFootprint(build);
        }
        DmShoppingStore dmShoppingStore = dmShoppingStoreMapper.selectDmShoppingStoreById(id);
        DanmoUserStore danmoUserStore = danmoUserStoreMapper.selectUSerId(userid, id);
        if (danmoUserStore == null){
            dmShoppingStore.setIsFollow(false);
        }else {
            dmShoppingStore.setIsFollow(true);
        }
        return dmShoppingStore;
    }

    private boolean isToday(Date date) {
        Date now = DateUtils.getNowDate();
        java.util.Calendar cal1 = java.util.Calendar.getInstance();
        java.util.Calendar cal2 = java.util.Calendar.getInstance();
        cal1.setTime(date);
        cal2.setTime(now);
        return cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)
                && cal1.get(java.util.Calendar.DAY_OF_YEAR) == cal2.get(java.util.Calendar.DAY_OF_YEAR);
    }

    @Override
    public DmShoppingStoreVO selectDmShoppingStoreByUserId(Long userId) {
        DmShoppingStoreVO dmShoppingStoreVO = new DmShoppingStoreVO();
        DmShoppingStore dmShoppingStore = dmShoppingStoreMapper.selectDmShoppingStoreByUserId(userId);
        if(null == dmShoppingStore){
            return null;
        }
        BeanUtil.copyProperties(dmShoppingStore,dmShoppingStoreVO);
        SecurityDepositAccount account = new LambdaQueryChainWrapper<>(securityDepositAccountMapper).eq(SecurityDepositAccount::getStoreId, dmShoppingStore.getId()).one();
        if(null != account){
            dmShoppingStoreVO.setSecurityDeposit(account.getSecurityDeposit());
            dmShoppingStoreVO.setSecurityAmount(account.getAmount());
            dmShoppingStoreVO.setSecurityAccountId(account.getId());
        }
        PremiumAccount premiumAccount = new LambdaQueryChainWrapper<>(premiumAccountMapper).eq(PremiumAccount::getStoreId, dmShoppingStore.getId()).one();
        dmShoppingStoreVO.setPremiumAmount(0);
        dmShoppingStoreVO.setPremium(dmShoppingStore.getType().getPremium());
        if(null != premiumAccount){
            dmShoppingStoreVO.setPremiumAmount(premiumAccount.getAmount());
            dmShoppingStoreVO.setPremiumAccountId(premiumAccount.getId());
        }
        return dmShoppingStoreVO;
    }

    /**
     * 查询商家信息列表
     *
     * @param dmShoppingStore 商家信息
     * @return 商家信息
     */
    @Override
    public List<DmShoppingStore> selectDmShoppingStoreList(DmShoppingStore dmShoppingStore) {
        return dmShoppingStoreMapper.selectDmShoppingStoreList(dmShoppingStore);
    }

    /**
     * 新增商家信息
     *
     * @param dmShoppingStore 商家信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int insertDmShoppingStore(DmShoppingStoreDTO dmShoppingStore) {
        // 验证验证码
        String redisKey = redis_key + dmShoppingStore.getTel();
        String captcha = stringRedisTemplate.opsForValue().get(redisKey);
        if(StrUtil.isEmpty(captcha) || !Integer.valueOf(captcha).equals(dmShoppingStore.getCaptcha())){
            throw new RuntimeException("验证码错误");
        }
        dmShoppingStore.setCreateTime(DateUtils.getNowDate());
        dmShoppingStore.setFansNumber(0L);
        dmShoppingStore.setState(3L);
//        dmShoppingStoreMapper.insertDmShoppingStore(dmShoppingStore);
        dmShoppingStoreMapper.insert(dmShoppingStore);
        // 新增保证金账户
        SecurityDepositAccount securityDepositAccount = new SecurityDepositAccount();
        securityDepositAccount.setStoreId(dmShoppingStore.getId());
        securityDepositAccount.setUserId(dmShoppingStore.getUserId());
        securityDepositAccount.setAmount(0);
        // 默认是 1千
        securityDepositAccount.setSecurityDeposit(100000);
        securityDepositAccountMapper.insert(securityDepositAccount);
        PremiumAccount premiumAccount = new PremiumAccount();
        premiumAccount.setStoreId(dmShoppingStore.getId());
        premiumAccount.setUserId(dmShoppingStore.getUserId());
        premiumAccount.setAmount(0);
        premiumAccountMapper.insert(premiumAccount);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void sendCode(String tel) {
        boolean mobile = Validator.isMobile(tel);
        if (!mobile) {
            throw new RuntimeException("手机号码格式错误");
        }
        String code = RandomUtil.randomNumbers(6);
        try {
            smsService.sendSms(tel,  code);
        } catch (ClientException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("发送验证码失败");
        }
        // 存入Redis，有效期5分钟
        String redisKey = redis_key + tel;
        stringRedisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 修改商家信息
     *
     * @param dmShoppingStore 商家信息
     * @return 结果
     */
    @Override
    public int updateDmShoppingStore(DmShoppingStore dmShoppingStore) {
        DmShoppingStore store = dmShoppingStoreMapper.selectById(dmShoppingStore.getId());
        if(store.getType().getCode() >  dmShoppingStore.getType().getCode()){
            throw new RuntimeException("当前商家类型不能降级");
        }
        PremiumAccount account = new LambdaQueryChainWrapper<>(premiumAccountMapper).eq(PremiumAccount::getStoreId, dmShoppingStore.getId()).one();
        if(dmShoppingStore.getType().getPremium() > account.getAmount()){
            dmShoppingStore.setState(3L);
        }
        dmShoppingStore.setUpdateTime(DateUtils.getNowDate());
        return dmShoppingStoreMapper.updateDmShoppingStore(dmShoppingStore);
    }

    /**
     * 批量删除商家信息
     *
     * @param ids 需要删除的商家信息主键
     * @return 结果
     */
    @Override
    public int deleteDmShoppingStoreByIds(Long[] ids) {
        return dmShoppingStoreMapper.deleteDmShoppingStoreByIds(ids);
    }

    /**
     * 删除商家信息信息
     *
     * @param id 商家信息主键
     * @return 结果
     */
    @Override
    public int deleteDmShoppingStoreById(Long id) {
        return dmShoppingStoreMapper.deleteDmShoppingStoreById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void closeStore(CloseStoreDTO closeStoreDTO) {
        // 查询当前商户是否还有 没有处理完成的订单
        Integer orderCount = dmShoppingStoreMapper.findOrderCount(closeStoreDTO.getStoreId());
        if(orderCount > 0){
            throw new RuntimeException("当前商户还有未处理完成的订单，请处理后再进行关闭");
        }
        new LambdaUpdateChainWrapper<>(dmShoppingStoreMapper).eq(DmShoppingStore::getId, closeStoreDTO.getStoreId())
                .set(DmShoppingStore::getState, 2).update();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void openStore(CloseStoreDTO closeStoreDTO) {
        SecurityDepositAccount account = new LambdaQueryChainWrapper<>(securityDepositAccountMapper).eq(SecurityDepositAccount::getStoreId, closeStoreDTO.getStoreId())
                .one();
        if(account.getAmount() < account.getSecurityDeposit()){
            throw new RuntimeException("保证金不足！");
        }
        new LambdaUpdateChainWrapper<>(dmShoppingStoreMapper).eq(DmShoppingStore::getId, closeStoreDTO.getStoreId())
                .set(DmShoppingStore::getState, 1).update();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void cancelStore(CloseStoreDTO closeStoreDTO) {
        DmShoppingStore one = new LambdaQueryChainWrapper<>(dmShoppingStoreMapper).eq(DmShoppingStore::getId, closeStoreDTO.getStoreId())
                .select(DmShoppingStore::getId, DmShoppingStore::getState).one();
        if (!one.getState().equals(2L)){
            throw new RuntimeException("需要关闭店铺");
        }
        dmShoppingStoreMapper.deleteById(one);
    }



}
